package com.lihao.wanandroid.ui.project

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.google.android.material.tabs.TabLayoutMediator
import com.kingja.loadsir.core.LoadService
import com.lihao.jetpackcore.ext.parseState
import com.lihao.jetpackcore.util.LogUtils
import com.lihao.jetpackcore.util.ToastUtil
import com.lihao.wanandroid.R
import com.lihao.wanandroid.app.base.BaseFragment
import com.lihao.wanandroid.app.ext.*
import kotlinx.android.synthetic.main.fragment_project_classify.*

/**
 * Created by lihao on 2020/5/19.
 * Describe: 项目Fragment
 */
class ProjectClassifyFragment : BaseFragment<ProjectViewModel>() {

    private val loadSir: LoadService<Any> by lazy {
        LoadServiceInit(viewPager) {
            // 重新加载
            loadSir.showLoading()
            mViewModel.getProjectTree()
        }
    }

    override fun layoutId() = R.layout.fragment_project_classify

    override fun initView(savedInstanceState: Bundle?) {
        initTitle("项目分类", false)
        viewPager.init(this, mViewModel.fragments, true)
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = mViewModel.tabTitles[position]
        }.attach()
        viewPager.currentItem = mViewModel.curViewPagerIndex
        viewPager.setPageListener {
            mViewModel.curViewPagerIndex = it
        }
    }

    override fun lazyLoadData() {
        loadSir.showLoading()
        mViewModel.getProjectTree()
    }

    override fun createObserver() {
        mViewModel.projectTree.observe(this, Observer { resultState ->
            parseState(resultState, {
                loadSir.showSuccess()
                // 添加fragment
                for (item in it) {
                    mViewModel.fragments.add(ProjectListFragment.newInstance(false, item.id))
                    mViewModel.tabTitles.add(item.name)
                }
                viewPager.adapter?.notifyDataSetChanged()
                TabLayoutMediator(tabLayout, viewPager) { tab, position ->
                    tab.text = mViewModel.tabTitles[position]
                }.attach()
            }, {
                loadSir.showError(it.errorMsg)
            })
        })
    }
}